package com.bjpowernode.mvc.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bjpowernode.common.client.FastDfsClient;
import com.bjpowernode.db.domain.HeaderImage;
import com.bjpowernode.db.mapper.HeaderImageMapper;
import com.bjpowernode.mvc.model.dto.user.HeaderImageDTO;
import com.bjpowernode.mvc.model.dto.user.SaveHeaderImageDTO;
import com.bjpowernode.mvc.service.inter.HeaderImageService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.Date;


@Service
public class HeaderImageServiceImpl implements HeaderImageService {


    @Resource
    private FastDfsClient fastDfsClient;

    @Resource
    private HeaderImageMapper headerImageMapper;

    //查看用户的头像
    @Override
    public HeaderImage queryUserId(Integer userId) {

        QueryWrapper<HeaderImage> wrapper = new QueryWrapper<>();
        wrapper.eq("uid", userId);

        return headerImageMapper.selectOne(wrapper);

    }


    //删除头像文件.
    @Override
    public boolean removeHeaderFromDFS(String groupName, String fileId) {

        return fastDfsClient.deleteFastDfs(groupName, fileId);
    }


    //从数据库删除.
    @Override
    public boolean deleteDB(Integer userId) {
        QueryWrapper<HeaderImage> wrapper = new QueryWrapper<>();
        wrapper.eq("uid", userId);
        int delete = headerImageMapper.delete(wrapper);
        return delete == 1;

    }



    //上传文件.
    @Override
    public SaveHeaderImageDTO saveFileFastDFS(HeaderImageDTO headerImageDTO) {
        SaveHeaderImageDTO saveHeaderImageDTO=fastDfsClient.uploadFile(headerImageDTO);

        return saveHeaderImageDTO;
    }

    //把文件信息和fastdto返回的结果存入数据库
    @Override
    public boolean addHeaderImage(HeaderImageDTO headerImageDTO) {
        HeaderImage record=new HeaderImage();
        record.setCreateTime(new Date());
        record.setUid(headerImageDTO.getUserId());
        record.setExtName(headerImageDTO.getExtName());
        record.setFileId(headerImageDTO.getFieldId());
        record.setGroupName(headerImageDTO.getGroup());
        record.setImgHeight(headerImageDTO.getHeight());
        record.setImgWidth(headerImageDTO.getWidth());
        int row=headerImageMapper.insert(record);
        return row ==1;
    }
}
